package com.dj.ms.event.support;

import com.dj.ms.event.EventBusHandler;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * <br>
 * <p>异步事件--事务切面</p>
 *
 * <br>
 *
 * @author ZJG
 * @version 1.0
 * @date 2021/7/26 下午7:18
 */
@Slf4j
@Aspect
@Component
public class AsyncEventTransactionAspect implements TransactionSynchronization {

    @Before("@annotation(org.springframework.transaction.annotation.Transactional)")
    public void registerTransactionSynchronization() {
        TransactionSynchronizationManager.registerSynchronization(this);
        EventBusHandler.inTransaction.set(true);
        log.debug("事务开始：{}", TransactionSynchronizationManager.getCurrentTransactionName());
    }

    /**
     * 事务提交后真正触发事件
     */
    @Override
    public void afterCommit() {
        log.debug("事务已提交，真正触发事件. 事务：{}", TransactionSynchronizationManager.getCurrentTransactionName());
        EventBusHandler.doAsyncPost();
    }

    @Override
    public void afterCompletion(int status) {
        if (status == STATUS_COMMITTED) {
            log.info("事务提交执行成功，正确完成. 事务：{}", TransactionSynchronizationManager.getCurrentTransactionName());
            EventBusHandler.inTransaction.remove();
        }
    }

}
